import time

from tool import iotDeviceSensorDataTool
from tool import iotDeviceSensorTool
from tool import iotDeviceSettingTool
from tool import iotDeviceTool
from tool import iotTokenTool
from util import httpTool


def refreshToken():
    req = {
        'apiKey': "${apiKey}",
        'apiSecret': "${apiSecret}"
    }
    iotTokenTool.refresh(req)
    print(httpTool.token)


def setToken():
    httpTool.setToken("")


def listDevice():
    req = {
        'status': 'ONLINE'
    }
    res = iotDeviceTool.list(req)
    if res:
        for device in  res:
            print(device['deviceCore'])

        deviceCoreList = []
        for i in range(len(res)):
            device = res[i]
            if i == 0:
                getDevice(device['deviceCore'])
            elif i < 5:
                deviceCoreList.append(device['deviceCore'])
                batchDeviceStatus(deviceCoreList)


def batchDeviceStatus(deviceCoreList):
    req = {
        'deviceCoreList': deviceCoreList
    }
    res = iotDeviceTool.batchDeviceStatus(req)
    if res:
        for i in range(len(res)):
            item = res[i]
            print(item['deviceCore'] + item['status'])


def getDevice(deviceCore):
    req = {
        'deviceCore': deviceCore
    }
    res = iotDeviceTool.get(req)
    if res:
        resDeviceCore = res['deviceCore']
        print(resDeviceCore)
        listSensor(resDeviceCore);
        listSetting(resDeviceCore);
        sendSetting(resDeviceCore);


def listSensor(deviceCore):
    req = {
        'deviceCore': deviceCore,
        'withParam': True,
        'withSetting': True,
        'withExplain': True,
    }
    res = iotDeviceSensorTool.list(req)
    if res:
        for i in range(len(res)):
            sensor = res[i]
            for j in range(len(sensor['explainList'])):
                explain = sensor['explainList'][j]
                print(explain['keyName'])
            for j in range(len(sensor['settingList'])):
                setting = sensor['settingList'][j]
                print(setting['keyName'])
            for j in range(len(sensor['paramList'])):
                param = sensor['paramList'][j]
                print(param['keyName'])


def listSensorDataWithExplain(deviceCore, port):
    t = time.time()
    endTime = int(t)
    startTime = endTime - (60 * 60 * 12)

    req = {
        'deviceCore': deviceCore,
        'port': port,
        'enableEval': True,
        'startTime': startTime,
        'endTime': endTime,
    }
    res = iotDeviceSensorDataTool.list(req)


def listSetting(deviceCore):
    req = {
        'deviceCore': deviceCore
    }
    res = iotDeviceSettingTool.list(req)
    if res:
        for i in range(len(res)):
            print(res[i].keyName)


def sendSetting(deviceCore):
    req = {
        'deviceCore': deviceCore,
        'keyName': "getData",
        'port': '0',
        'value': ''
    }
    res = iotDeviceSettingTool.send(req)


if __name__ == '__main__':
    refreshToken()
    listDevice()
